-module(queue_json).
-include("rec_dec.hrl").
-export([list/0,detail/1,delete/1]).

list() ->
    L = biz_queue:items(list),
    J_Objs = lists:map(fun(Q) ->
                R = Q#queue_inst_rec.q_rec,
                Custs = queue_inst:get_cust_info(R#queue_rec.name),
                io:format("Q:~s Cust:~p ~n",[R#queue_rec.name,Custs]),
                    {obj,
                        [
                            {
                            "name",list_to_binary(R#queue_rec.name)
                            }
                            ,{
                            "desc",list_to_binary(R#queue_rec.desc)
                            }
                            ,{
                            "max_len",R#queue_rec.max_len
                            }
                            ,{
                            "cust_num",queue_inst:get_cust_num(R#queue_rec.name)
                            }
                            ,{"next_cust",dump_next_cust(Custs)}
                        ]
                    }
                end,
                L),
    rfc4627:encode(J_Objs).
    
    
detail(QName) ->
    Items = queue_inst:get_cust_info(QName),
    J_Objs = lists:map(fun(C) ->   
                            dump_cust(C)
                       end,
                       Items),
    rfc4627:encode(J_Objs).

	
delete(QName) ->
	biz_queue:del_queue(QName),
	J_Objs = {obj,[{"result",list_to_binary("OK")}]},
	rfc4627:encode(J_Objs).
	
%%%%%%%%%%%%%%Cust%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
dump_next_cust([]) ->
    {obj,[]};
dump_next_cust([Cust|_]) ->
    dump_cust(Cust).
    
%% dump a cust record into JSON info
dump_cust(C) ->
    io:format("~p~n",[C]),
	{Hour,Min,Sec} = C#cust_in_q_rec.in_q_time,
    {obj,[
        {"name",list_to_binary(C#cust_in_q_rec.name)}
        ,{"mobile_phone",list_to_binary(C#cust_in_q_rec.mobile_phone)}
        ,{"index",C#cust_in_q_rec.index}
        ,{"loc",C#cust_in_q_rec.loc}
        ,{"sms_sent_times",C#cust_in_q_rec.sms_sent_times}
        ,{"in_q_time",list_to_binary(io_lib:format("~B-~B-~B",[Hour,Min,Sec]))}
    ]}.
